package org.biubiu0002.baiblog.core.async.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.common.constants.CacheConstants;
import org.biubiu0002.baiblog.common.constants.MqConstants;
import org.biubiu0002.baiblog.core.async.event.UpdateUserStatusEvent;
import org.biubiu0002.baiblog.core.config.RabbitMqConfig;
import org.biubiu0002.baiblog.core.model.entity.ShareEntity;
import org.biubiu0002.baiblog.core.service.RichTextService;
import org.biubiu0002.baiblog.core.service.ShareService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-22 17:37
 **/
@RabbitListener(queues = RabbitMqConfig.UPDATE_USER_STATUS_QUEUE)
@Component
@Slf4j
public class UpdateUserStatusListener {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Resource
    private ShareService shareService;

    @Resource
    private RichTextService richTextService;


    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(msg));
            UpdateUserStatusEvent updateUserStatusEvent = JSON.parseObject(msg, UpdateUserStatusEvent.class);
            String userUid = updateUserStatusEvent.getUserUid();
            Integer newStatus = updateUserStatusEvent.getNewStatus();

            log.info("====消费者: {} 收到消息: {} ",MqConstants.UPDATE_USER_STATUS_QUEUE,updateUserStatusEvent);
            //1.调整这个用户的所有推文的状态
            List<ShareEntity> shareListByUserUid = shareService.getShareAllListByUserUid(userUid);
            List<String> shareIdList = shareListByUserUid.stream().map(ShareEntity::getResourceId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(shareIdList)){
                //1.1更新数据库状态 更新帖子 文本内容 的状态
                shareService.updateShareListStatus(shareIdList,newStatus);
                richTextService.updateShareTextStatus(shareIdList,newStatus);
                //1.2删除推文详情缓存
                List<String> shareInfoKeys = shareIdList.stream().map(CacheConstants::getShareInfoKey).collect(Collectors.toList());
                redisTemplate.delete(shareInfoKeys);
                if(newStatus!=0){
                    //1.3删除榜单中的数据
                    for (String shareId : shareIdList) {
                        shareService.removeFromLikeCountBoard(shareId);
                        shareService.removeFromLatestBoard(shareId);
                    }
                }
                else {
                    //1.3恢复榜单中的数据
                    for (String shareId : shareIdList) {
                        shareService.recoverFromLikeCountBoard(shareId);
                        shareService.recoverFromLatestBoard(shareId);
                    }
                }
            }
            channel.basicAck(deliveryTag,false);
        }
        catch (Exception e){
            if (Boolean.TRUE.equals(message.getMessageProperties().isRedelivered())) {
                log.error("[消费拒绝]:{}",message,e);
                channel.basicReject(deliveryTag, false);
            } else {
                log.warn("[消费重试]:{}",message,e);
                channel.basicNack(deliveryTag, false, true);
            }
        }

    }
}
